//
//  UIImageView+HKExtension.swift
//  WeiBo
//
//  Created by 胡锦涛 on 2018/12/25.
//  Copyright © 2018 胡锦涛. All rights reserved.
//

import Foundation
import Kingfisher

extension UIImageView {
    
    func setImage(_ url: String, placeholderImage: UIImage?, completion:(() -> Void)? = nil) {
        kf.cancelDownloadTask()
        kf.setImage(with: URL(string: url), placeholder: placeholderImage, options: nil, progressBlock: nil) { (_, error, _, _) in
            if error == nil && completion != nil {
                completion!()
            }
        }
    }
    
}

extension UIButton {
    
    func setImage(_ url: String,for state: UIControl.State,placeholderImage: UIImage?,completion:(() -> Void)? = nil) {
        kf.cancelImageDownloadTask()
        kf.setImage(with: URL(string: url), for: state, placeholder: placeholderImage, options: nil, progressBlock: nil) { (_, error, _, _) in
            if error == nil && completion != nil {
                completion!()
            }
        }
    }
    
    func setBackgroundImage(_ url: String,for state: UIControl.State,placeholderImage: UIImage?,completion:(() -> Void)? = nil) {
        kf.cancelBackgroundImageDownloadTask()
        kf.setBackgroundImage(with: URL(string: url), for: state, placeholder: placeholderImage, options: nil, progressBlock: nil) { (_, error, _, _) in
            if error == nil && completion != nil {
                completion!()
            }
        }
    }
}

func calculateDiskImageCacheSize(_ completion: @escaping ((CGFloat) -> Void)) {
    ImageCache.default.calculateDiskCacheSize { (size) in
        completion(CGFloat(size)/1024/1024)
    }
}

func clearDiskImageCache(_ completion:@escaping (() -> Void)) {
    ImageCache.default.clearDiskCache {
        completion()
    }
}
